package com.m4f.business.service;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
import javax.cache.CacheException;
import org.mcavallo.opencloud.Tag;
import com.m4f.business.model.Company;
import com.m4f.business.service.helper.TagsCloud;
import com.m4f.business.service.ifc.ICompanyService;

public class TagsCloudService {
	
	private static final Logger LOGGER = Logger.getLogger(TagsCloudService.class.getName());
	
	private ICompanyService companyService;
	private TagsCloud cloud;
	
	public TagsCloudService(CompanyService compService) 
		throws CacheException, IOException {
		this.companyService = compService;
		this.cloud = new TagsCloud();
	}
	
	public TagsCloud getTagsCloud() 
		throws IOException, ClassNotFoundException  {
		if(this.cloud == null) {
			this.loadTagsCloud();
		}
		return this.cloud;
	}
	
	public void clearTagsCloud() {
		this.cloud.clear();
	}
	
	
	
	/*************************************************************************
	 * 
	 *							PRIVATE METHODS
	 *
	 *************************************************************************/
	
	
	/**
	 * 
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	private void loadTagsCloud() 
		throws IOException, ClassNotFoundException {
		this.cloud = new TagsCloud();
		List<Company> companies = companyService.getCompanies();
		cloud = this.loadTagsCloud(companies);
	}
	
	
	private TagsCloud loadTagsCloud(List<Company> companies) {
		TagsCloud cloud = new TagsCloud();
		cloud.setDefaultLink("%s");
		cloud.setMaxTagsToDisplay(100);
		// We want four different levels so set the maximum weight value to 4.0.
		cloud.setMinWeight(1.0);
		cloud.setMaxWeight(250.0);	
		for(Company company : companies) {
			if(company.getCompanyInfo()==null || 
					company.getCompanyInfo().getSicCode()==null) {
				continue;
			}
			if(!company.isValidated()) {
				continue;
			}
			/**SicCode loaded*/
			if(!"".equals(company.getCompanyInfo().getSicCode())) {
				Tag tag = new Tag("sicCode." + company.getCompanyInfo().getSicCode(),
						company.getCompanyInfo().getSicCode(), 1.0);
				cloud.addTag(tag);
			}
		}
		return cloud;
	}
}